/*
 * Created: 2022-08-29 21:56:08
 * Author : 涛涛涛
 */
import React, { createContext, useState, useReducer, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { apiGetIntactProductList } from '@/pages/_server/_api/ApiProduct/apiGetIntactProductList';
import { createReducerMapper, useMyReducer } from '@/utils/index';
import { Product_Web } from '../_server/_class/Product/Product';
export type HomeContextType = {
    homeExhibitionState: HomeExhibition;
};
export const HomeContext = createContext<HomeContextType>(undefined);

/** 页面渲染的列表 */
export type HomeExhibition = {
    productList: Product_Web[];
    bannerList: Product_Web[];
    gotoPageDetail: (productId: string) => void;
};

/** 处理reducer的函数 */
const handleMapper = createReducerMapper({
    initializer: null as HomeExhibition,
    handleMapper: {
        /** 刷新列表 */
        freshList: (state, payload?: { productList: Product_Web[] }) => {
            let list = [...payload.productList];
            let newState: Pick<HomeExhibition, 'productList' | 'bannerList'> = {
                productList: [],
                bannerList: [],
            };
            newState.productList = [...list];
            list.length > 8 && (list.length = 8);
            newState.bannerList = [...list];
            return { ...state, ...newState };
        },
    },
});

const initialState: HomeExhibition = {
    productList: [],
    bannerList: [],
    gotoPageDetail: (productId: string) => {
        Taro.redirectTo({
            url: `pages/ProductExhibition/ProductExhibition?productId=${productId}`,
        });
    },
};

/** 使用需要展示的列表 */
export const useHomeExhibitionList = () => {
    const [homeExhibitionState, homeExhibitionDispatch] = useMyReducer({
        initializer: initialState,
        handleMapper,
    });
    useEffect(() => {
        // 页面加载完成时初始化列表
        apiGetIntactProductList().then(async (res) => {
            homeExhibitionDispatch({
                type: 'freshList',
                payload: {
                    productList: res.data,
                },
            });
        });
    }, [homeExhibitionDispatch]);
    return {
        homeExhibitionState,
    };
};
